package com.easepal802s.project.application;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;

import androidx.core.app.ActivityCompat;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.easepal.project.uikit.UikitManager;
import com.ogawa.a7517.BuildConfig;
import com.ogawa.base.Constant.BleConstant;
import com.easepal802s.project.ui.activity.ChooseActivity;
import com.easepal802s.project.ui.activity.SplashActivity;
import com.example.reslib.utils.PreferenceWrapper;
import com.ogawa.base.utils.ActivityManager;
import com.ogawa.base.utils.CommonUtil;
import com.ogawa.networklib.RetrofitManager;
import com.ogawa.networklib.networkBean.AddressBean;
import com.tencent.bugly.crashreport.CrashReport;
import com.trello.rxlifecycle3.components.support.RxAppCompatActivity;
import com.umeng.commonsdk.UMConfigure;
import com.yanzhenjie.permission.AndPermission;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * Created by FHB on 2018/4/10.
 */
public class MyApplication extends MultiDexApplication {
    public static Context mContext;
    private int activityAccount = 0;

    @Override
    public void onCreate() {
        super.onCreate();

        initARouter();

        mContext = getApplicationContext();
        PreferenceWrapper.init(mContext);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();


        BleManager.getInstance().init(this);
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setServiceUuids(new UUID[]{UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb")})      // 只扫描指定的服务的设备，可选
//                .setDeviceName(true, names)         // 只扫描指定广播名的设备，可选
//                .setDeviceMac(mac)                  // 只扫描指定mac的设备，可选
//                .setAutoConnect(isAutoConnect)      // 连接时的autoConnect参数，可选，默认false
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        //数据收集
        UikitManager uikitManager = UikitManager.getInstance();
        uikitManager.registerSdkWithAppId(BleConstant.APPID);//
        uikitManager.registerSdkWithRsaPrivate(BleConstant.RSA);
//        initBugly();
//        initUM();
        initActivityLifecycleCallbacks();
    }

    /**
     * 初始化友盟相关配置
     */
    private void initUM() {
        // 友盟初始化
        UMConfigure.setLogEnabled(true);// 设置 LOG 开关，默认为 false
        UMConfigure.setEncryptEnabled(false);// 设置日志加密
        /*
         * 初始化组建基础库（common库）
         * 参数1：上下文
         * 参数2：【友盟+】AppKey
         * 参数3：【友盟+】Channel
         * 参数4：设备类型，DEVICE_TYPE_PHONE：手机，DEVICE_TYPE_BOX：盒子，默认为手机
         * 参数5：Push 推送业务的 secret，需要集成 Push 功能时必须传入 Push 的 secret，否则为空
         */
        UMConfigure.init(this, "5e1fdad54ca3576d37000645", "Umeng", UMConfigure.DEVICE_TYPE_BOX, null);
//        MobclickAgent.openActivityDurationTrack(false);
    }

    /**
     * 初始化腾讯 Bugly
     */
    private void initBugly() {
        /*
         * 初始化 Bugly
         * 参数1：上下文
         * 参数2：注册时申请的APPID
         * 参数3：SDK调试模式开关，调试模式的行为特性如下：
         * - 输出详细的 Bugly SDK的Log；
         * - 每一条Crash都会被立即上报；
         * - 自定义日志将会在Logcat中输出。
         * 建议在测试阶段建议设置成 true，发布时设置为 false。
         */
        CrashReport.initCrashReport(getApplicationContext(), "79ddf60b9c", false);
    }

    public static Context getContext() {
        return mContext;
    }

    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }


    /**
     * 在application里监听所以activity生命周期的回调
     */
    private void initActivityLifecycleCallbacks() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() { //添加监听
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                //activity创建生命周期
                ActivityManager.getInstance().addActivity(activity);
                LogUtils.e(activity.getLocalClassName() + " - onActivityCreated");
            }

            @Override
            public void onActivityStarted(Activity activity) {
                LogUtils.i(activity.getLocalClassName() + " - onActivityStarted");
                //activity启动生命周期
                if (activityAccount == 0) {
                    //app回到前台
                    if (!(activity instanceof ChooseActivity)
                            && !(activity instanceof SplashActivity)) {
                        getLocation();
                    }
                }
                activityAccount++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                LogUtils.i(activity.getLocalClassName() + " - onActivityResumed");
                //activity恢复生命周期
                if (activity instanceof ChooseActivity) {
                    getLocation();
                }
//                double longitude = location.getLongitude();
//                double latitude = location.getLatitude();
//                Address address = LocationUtils.getLocationInfo(longitude, latitude, MyApplication.this);
//                for (int i = 0; address.getAddressLine(i) != null; i++) {
//                    Log.e("tag", "-------------------" + address.getAddressLine(i));
//                }
//                Log.e("tag", longitude + "----------" + latitude + "--------------");
            }

            @Override
            public void onActivityPaused(Activity activity) {
                //activity暂停生命周期
                LogUtils.i(activity.getLocalClassName() + " - onActivityPaused");
            }

            @Override
            public void onActivityStopped(Activity activity) {
                //activity停止生命周期
                LogUtils.i(activity.getLocalClassName() + " - onActivityStopped");
                activityAccount--;
                if (activityAccount == 0) {
                    //从前台切到后台
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                //保存activity实例状态

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                //activity销毁生命周期
                ActivityManager.getInstance().removeActivity(activity);
                LogUtils.e(activity.getLocalClassName() + " - onActivityDestroyed");
            }
        });
    }

    private void getLocation() {
        AndPermission.with(this)
                .runtime()
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION
                        , Manifest.permission.ACCESS_FINE_LOCATION)
                .onGranted(data -> {
                    //获取系统的LocationManager对象
                    final LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                    if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        /*
                         * 进行定位
                         * provider:用于定位的locationProvider字符串:LocationManager.NETWORK_PROVIDER/LocationManager.GPS_PROVIDER
                         * minTime:时间更新间隔。单位：ms
                         * minDistance:位置刷新距离，单位：m
                         * listener:用于定位更新的监听者locationListener
                         */
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        mLocationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, new LocationListener() {
                            @Override
                            public void onLocationChanged(Location location) {
                                try{
                                    updateLocation(location);
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onStatusChanged(String s, int i, Bundle bundle) {

                            }

                            @Override
                            public void onProviderEnabled(String s) {

                            }

                            @Override
                            public void onProviderDisabled(String s) {

                            }
                        }, null);
                    } else {

                    }
                })
                .onDenied(data -> {
                }).start();
    }

    private Address getLocationInfo(double lng, double lat) {
        Address address = null;
        Geocoder gc = new Geocoder(this, Locale.getDefault());
        List<Address> locationList = null;
        try {
            locationList = gc.getFromLocation(lat, lng, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (locationList == null) {
            return null;
        }
        address = locationList.get(0);//得到Address实例
        return address;
    }

    private void updateLocation(Location location) {
        if (location == null) {
            return;
        }
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        Address address = getLocationInfo(longitude, latitude);
        if (address != null){
            AddressBean bean = new AddressBean();
            bean.setAppVersion(CommonUtil.getVersionCode(this));
            bean.setPhoneId(CommonUtil.getAndroidId(this));
            bean.setLongitude(String.valueOf(longitude));
            bean.setLatitude(String.valueOf(latitude));
            bean.setCountry(address.getCountryName());
            bean.setProvince(address.getAdminArea());
            bean.setCity(address.getLocality());
            bean.setDistrict(address.getSubLocality());
            bean.setAddress(address.getFeatureName());
            RetrofitManager instance = RetrofitManager.getInstance();
            instance.getData(instance.getApiService().updateAddress(bean)
                    , null, (RxAppCompatActivity) null);
        }

    }


    void initARouter() {
        if (BuildConfig.DEBUG){
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(this);
    }

}
